//
//  FlickrSearchResultsModel.m
//
//  Created by Keith Lazuka on 7/23/09.
//  
//

#import "NeedsResultsModel.h"
#import "NeedsJSONResponse.h"
//#import "NeedishXMLResponse.h"
#import "GTMNSDictionary+URLArguments.h"
#import "NSData+Base64.h"
#import "NeedishStore.h"

const static NSUInteger kNeedishBatchSize = 16;   // The number of results to pull down with each request to the server.

@implementation NeedsResultsModel

@synthesize searchTerms;

- (id)initWithResponseFormat:(NeedResponseFormat)responseFormat kind: (NSString*)kind method: (NSString*)method limit:(int) limit;
{
    if ((self = [super init])) {
        switch ( responseFormat ) {
            case NeedResponseFormatJSON:
                responseProcessor = [[NeedsJSONResponse alloc] init];
				_apiMethod = method;
				_apiKind = kind;
				_limit = limit;
                break;
            case NeedResponseFormatXML:
//                responseProcessor = [[NeedsXMLResponse alloc] init];
//				_apiMethod = method;
//				_apiKind = kind;
//				_limit = limit;
                break;
            default:
                [NSException raise:@"NeedsJSONResponse unknown!" format:nil];
        }
        page = 1;
    }
    return self;
}

- (id)init
{
    return [self initWithResponseFormat:CurrentNeedResponseFormat kind:_apiKind method:_apiMethod limit:_limit];
}

- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more
{
	if (more)
        page++;
    else
        [responseProcessor.objects removeAllObjects]; // Clear out data from previous request.
    
	
	
	NSString *batchSize = [NSString stringWithFormat:@"%i", _limit];
	
	//NSData *decodedData = [NSData dataFromBase64String:[[NSUserDefaults standardUserDefaults] stringForKey:@"INSessionSecret"]];  
	NSString *_username = [NeedishStore getUserName];// [[NSUserDefaults standardUserDefaults] stringForKey:@"INLastLoginEmail"]; 
	NSString *_password = [NeedishStore getPasswordForUsername:_username];//[[[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding] autorelease];
	
	NSString *path = [NSString stringWithFormat:@"/%@/%@.%@",_apiKind, _apiMethod, [responseProcessor format]];
	NSString *host = @"http://api.needish.com";

	NSDictionary *parameters;
	if (_limit > 0) {
		parameters = [NSDictionary dictionaryWithObjectsAndKeys:
						@"95c84893b0e2b86fc08eef6e6d5d63ac", @"api_key", // I am providing my own API key
						batchSize, @"limit",
						nil];		
	}
	else {
		parameters = [NSDictionary dictionaryWithObjectsAndKeys:
						@"95c84893b0e2b86fc08eef6e6d5d63ac", @"api_key", // I am providing my own API key
						nil];		
	}


	NSString *url = [host stringByAppendingFormat:@"%@?%@", path, [parameters gtm_httpArgumentsString]];
	
	
	NSString *authStr = [NSString stringWithFormat:@"%@:%@", _username, _password];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];

	
	TTURLRequest *request = [TTURLRequest requestWithURL:url delegate:self];
	[request setValue:authValue forHTTPHeaderField:@"Authorization"];
    request.cachePolicy = cachePolicy;
    request.response = responseProcessor;
    request.httpMethod = @"GET";

    [request send];
}
//
//-(void)request:(TTURLRequest*)request didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
//{
//    if ([challenge previousFailureCount] == 0) {
//		TTLOG(@"Try Password (NeedishModel) %@", [challenge previousFailureCount]);
//        NSURLCredential *newCredential;
//        newCredential=[NSURLCredential credentialWithUser:[[NSUserDefaults standardUserDefaults] stringForKey:@"INLastLoginEmail"] 
//                                                 password:[[NSUserDefaults standardUserDefaults] stringForKey:@"INSessionSecret"]
//                                              persistence:NSURLCredentialPersistenceNone];
//        [[challenge sender] useCredential:newCredential
//               forAuthenticationChallenge:challenge];
//    } else {
//		TTLOG(@"ERROR: Try Password (NeedishModel)");
//     //   [[challenge sender] cancelAuthenticationChallenge:challenge];
//        // inform the user that the user name and password
//        // in the preferences are incorrect
////        [self showPreferencesCredentialsAreIncorrectPanel:self];
////		TTLOG(@"ERROR: Try Password (NeedishModel)");
//	}
//}

- (void)reset
{
    [super reset];
    [searchTerms release];
    searchTerms = nil;
    page = 1;
    [[responseProcessor objects] removeAllObjects];
}

- (void)setSearchTerms:(NSString *)theSearchTerms
{
    if (![theSearchTerms isEqualToString:searchTerms]) {
        [searchTerms release];
        searchTerms = [theSearchTerms retain];
        page = 1;
    }
}

- (NSArray *)results
{
    return [[[responseProcessor objects] copy] autorelease];
}

- (NSUInteger)totalResultsAvailableOnServer
{
    return [responseProcessor totalObjectsAvailableOnServer];
}

- (void)dealloc
{
    [searchTerms release];
    [responseProcessor release];
    [super dealloc];
}


@end
